package com.alinesno.cloud.base.storage.service.strategy;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alinesno.cloud.base.storage.config.StorageLocalConfig;
import com.alinesno.cloud.base.storage.entity.StorageFileEntity;
import com.alinesno.cloud.base.storage.service.IStorageFileService;
import com.alinesno.cloud.base.storage.service.StorageService;

import cn.hutool.core.util.IdUtil;

/**
 * 本地存储
 * 
 * @author LuoAnDong
 * @since 2019年4月9日 下午8:43:34
 */
@Service("localStorageService")
public class LocalStrageServiceImpl implements StorageService {

	// 日志记录
	private final static Logger log = LoggerFactory.getLogger(QiniuStorageServiceImpl.class);

	// 本地保存路径A
	@Autowired
	private StorageLocalConfig storageLocalConfig;
	
	@Autowired
	private IStorageFileService storageFileService ; 

	@Override
	public String uploadData(String fileLoalAbcPath) {
		return null;
	}

	@Override
	public String downloadData(String fileId) {
		return null;
	}

	@Override
	public boolean deleteData(String fileId) {
		return false;
	}

	@Override
	public StorageFileEntity uploadData(String fileLoalAbcPath, String fileName)  throws Exception{
		log.debug("localSavePath:{} , abcPath:{} , fileName:{}", storageLocalConfig.getSavePath(), fileLoalAbcPath,fileName);
		File file = new File(fileLoalAbcPath);
		
		String id = IdUtil.createSnowflake(1, 2).nextId() + "";
		StorageFileEntity dbFile = new StorageFileEntity();
		dbFile.setFileName(fileName);
		dbFile.setFileSize(BigDecimal.valueOf(file.getTotalSpace()));

		Date date = new Date();
		String localPath = new SimpleDateFormat("yyyy/MM/dd/").format(date);
		String newFileName= id+fileName.substring(fileName.lastIndexOf("."));

		String path = storageLocalConfig.getSavePath() + "/" + localPath;
		File f = new File(path); // 如果不存在,创建文件夹

		if (!f.exists()) {
			FileUtils.forceMkdir(f);
		}

		try {
			FileUtils.copyFile(file, new File(path + "/" + newFileName));
			dbFile.setUrlDisk(localPath + "/" + newFileName);
		} catch (IOException e) {
			e.printStackTrace();
		}

		storageFileService.save(dbFile) ; 

		return dbFile;
	}

}
